package com.nbsaas.boot;

import javax.script.*;
import java.util.*;

public class KotlinScriptEvalDemo {

    public static void main(String[] args) throws ScriptException {
        // 获取 Kotlin 脚本引擎
        ScriptEngine engine = new ScriptEngineManager(KotlinScriptEvalDemo.class.getClassLoader())
                .getEngineByExtension("kts");

        if (engine == null) {
            throw new RuntimeException("Kotlin ScriptEngine not found! 请检查依赖");
        }

        // 循环执行脚本
        for (int i = 0; i < 3; i++) {
            // 每次创建新的 Bindings
            Bindings bindings = engine.createBindings();
            bindings.put("numbers", Arrays.asList(i, i * 2, i * 3));

            // 脚本内容，可以多行
            String script = ""
                    + "val total = numbers.sum()\n"
                    + "println(\"Numbers sum: $total\")\n"
                    + "total"; // 最后一行作为返回值

            // 每次直接 eval，动态解析和执行
            Object result = engine.eval(script, bindings);

            System.out.println("Result: " + result);
        }
    }
}
